<template>
  <div ref="chartDom" style="height:300px;width:100%"></div>
</template>
<script>
import { addListener, removeListener } from "resize-detector";
import debounce from "lodash/debounce";
export default {
  name: "Chart",
  props: {
    options: {
      type: Object,
      default: () => {},
    },
  },
  data: function() {
    return {
      chart: null,
    };
  },
  watch: {
    // 深度监听耗性能
    // options: {
    //   handler(val) {
    //     this.chart.setOption(val);
    //   },
    //   deep: true,
    // },
    options(val) {
      this.chart.setOption(val);
    },
  },
  created() {
    //防抖动
    this.resize = debounce(this.resize, 300);
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts();
    });
  },
  beforeDestroy() {
    removeListener(this.$refs.chartDom, this.resize);
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initCharts() {
      // 基于准备好的dom，初始化echarts实例
      this.renderChart();
      addListener(this.$refs.chartDom, this.resize);
    },
    resize() {
      console.log("resize");
      this.chart.resize();
    },
    renderChart() {
      this.chart = this.$echarts.init(this.$refs.chartDom);
      this.chart.setOption(this.options);
    },
  },
};
</script>
